package extend.org.compiere.hrm;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.LinkedHashMap;
import java.util.logging.Level;

import org.compiere.process.FI_SubcontoAnalyze;
import org.compiere.process.FI_SubcontoAnalyze.FI_SubcontoType;
import org.compiere.util.CLogger;
import org.compiere.util.DB;

public class Reserve {
	private static CLogger s_log = CLogger.getCLogger(FI_SubcontoAnalyze.class);
	
	private LinkedHashMap<Integer,BigDecimal> sectional = new LinkedHashMap<Integer, BigDecimal>();
	
	public Reserve(int C_BPartner_ID, Timestamp datefrom, int hrm_reserve_id, int account_id) {
	    PreparedStatement pstmt = null;
		ResultSet rs = null;		
		try {
			pstmt = DB.prepareStatement(getSql(),null);
			pstmt.setInt(1,C_BPartner_ID);
			pstmt.setInt(2,hrm_reserve_id);
			pstmt.setTimestamp(3, datefrom);
			pstmt.setInt(4, account_id);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				this.setSectional(rs.getInt("hrm_reservesectional_id"), new BigDecimal(rs.getDouble("amtacct")));
			}
		}
		catch (SQLException e)
		{
			s_log.log(Level.SEVERE, "product", e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}	
	}
	
	public BigDecimal getSectional(int hrm_reservesectional_id) {
		BigDecimal result = null;
		result = (BigDecimal) sectional.get(hrm_reservesectional_id);
		return (result == null ? new BigDecimal(0) : result);
	}
	
	private void setSectional(int hrm_reservesectional_id, BigDecimal ammount) {
		sectional.put(hrm_reservesectional_id, ammount);
	}
	
	private String getSql() {
		String result =  " with t1 as ( \n"
						+" select ad_org_id \n"
						+"      , ad_client_id \n"
						+"      , c_bpartner_id \n"
						+"      , hrm_reserve_id \n"
						+"      , hrm_reservesectional_id \n"
						+"      , sum(amtsourcedr) as amtsourcedr \n"
						+"      , sum(amtsourcecr) as amtsourcecr \n"
						+"      , sum(amtacctdr) as amtacctdr \n"
						+"      , sum(amtacctcr) as amtacctcr \n"
						+" from adempiere.v_fi_fact_acct_with_subconto \n"
						+" where hrm_reserve_id is not null and IsActive = 'Y' and \n" 
						+" c_bpartner_id = ? \n" 
						+" and hrm_reserve_id = ? \n" 
						+" and dateacct < ? \n" 
						+" and account_id = ? \n "
						+" group by ad_org_id \n"
						+"      , ad_client_id \n"
						+"      , c_bpartner_id \n"
						+"      , hrm_reserve_id \n"
						+"      , hrm_reservesectional_id \n"
						+" ) \n"
						+" select ad_org_id \n"
						+"      , ad_client_id \n"
						+"      , c_bpartner_id \n"
						+"      , hrm_reserve_id \n"
						+"      , hrm_reservesectional_id \n"
						+"      , amtsourcecr - amtsourcedr as amtsource      \n"
						+"      , amtacctcr - amtacctdr as amtacct \n"
						+" from t1 \n"
						+" order by C_BPartner_ID";
		return result;
	}
	
}

